﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Interface
{
    public class AMZOrderDetailDetailInterfaceBusiness : Interface_BaseBusiness, IJob_Business, ITransientDependency
    {
        public List<OL_FilterDTO> Filters;
        public int date = 0;

        public AMZOrderDetailDetailInterfaceBusiness()
        {
            this.InterfaceName = "领星亚马逊订单明细";
            //获取字段的映射关系
            tableField = GetMapField("addRow");
            //索引字段
            Keys = GetKeys("addRow");
            indexFields.Add(Keys.Where(X => X.Type == "K").First().Field);
            //查询过滤条件
            Filters = new List<OL_FilterDTO>();


            //查询执行前的事件
            BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //执行非查询请求中的事件
            OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="noQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, NoQueryEventArgs noQueryEventArgs)
        {
            //API请求是否成功
            noQueryEventArgs.Success = noQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_BeforeQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //执行查询前添加过滤条件
            if (queryEventArgs.Page.Filters.IsNullOrEmpty() && !Filters.IsNullOrEmpty())
            {
                queryEventArgs.Page.Filters = Filters;
            }

        }

        /// <summary>
        /// 查询执行中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //是否查询完成
            if (queryEventArgs.Result["data"]["rows"].ToList().Count == 0)
            {
                queryEventArgs.Page.Complete = true;
            }
            //向总行中添加新的行
            queryEventArgs.Rows.AddRange(queryEventArgs.Result["data"]["rows"].ToList());
            //获取总页数
            queryEventArgs.Page.Total = queryEventArgs.Result["data"]["total"].ToString().ToInt();
            //获取查询成功标志
            queryEventArgs.Success = queryEventArgs.Result["success"].ToString().ToBool();
        }


        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {

            try
            {
                //数据库连接
                ConString = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
                SqlDb = (SqlServerHelper)DbHelperFactory.GetDbHelper(EFCore.Sharding.DatabaseType.SqlServer, ConString);

                //获取此接口的所有API信息
                this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
                Base_InterfaceOption queryOption = this.interfaceOption.Where(o => o.OperateType == "getFilterRows").First();//查询API配置
                Base_InterfaceOption insertOption = this.interfaceOption.Where(o => o.OperateType == "addRow").First();//新增API配置
                Base_InterfaceOption upDateOption = this.interfaceOption.Where(o => o.OperateType == "editRow").First();//更行API配置
                Base_InterfaceOption deleteOption = this.interfaceOption.Where(o => o.OperateType == "deleteRow").First();//删除API配置
                Base_InterfaceOption LX_QueryOption = this.interfaceOption.Where(o => o.OperateType == "LX_Query").First();//领星API配置
                this.date = LX_QueryOption.ExcInterval;
                //获取查询参数(ONE_LINK亚马逊订单号)
                AMZOrderInterfaceBusiness AMZOrderBus = new AMZOrderInterfaceBusiness();
                AMZOrderBus.Filters.Clear();
                AMZOrderBus.Filters.Add(
                    //13:>,14>=15:<,16<=  查询报表创建时间pull_date
                    new OL_FilterDTO()
                    {
                        ControlId = "676a2dc69e0bc69bf1875baf",
                        DataType = 15,
                        SpliceType = 2,
                        FilterType = 14,
                        Value = DateTime.Now.AddDays(-date).ToString("yyyy-MM-dd"),
                    });
                //获取订单列表
                List<AMZOrder> AMZOrders = await AMZOrderBus.QueryAsync<AMZOrder>(AMZOrderBus.queryOption, AMZOrderBus.tableField, AMZOrderBus.SqlDb);

                //单据数量大于0,查询源数据

                if (AMZOrders.Count > 0)
                {
                    var orders = AMZOrders.Select(x => x.amazon_order_id).GroupBy(x => x).Select(x => x.FirstOrDefault()).ToList();
                    LX_AMZOrderDetailInterfaceBusiness AMZOrderDetailBus = new LX_AMZOrderDetailInterfaceBusiness();
                    AMZOrderDetailBus.reqDTO_A.orders = orders.Distinct().ToList();
                    List<AMZOrderDetail> sourceData_i = await AMZOrderDetailBus.QueryAsync<AMZOrderDetail>(AMZOrderDetailBus.LX_Query, AMZOrderDetailBus.SqlDb);
                    List<AMZOrderDetail> sourceData = new List<AMZOrderDetail>();
                    //订单明细赋值
                    sourceData_i.ForEach(r =>
                    {
                        r.item_list.ForEach(x =>
                        {
                            if (r.amazon_order_id == "112-1196786-5354657")
                            {
                                var ww = "114-4613120-8582654";

                            }
                            AMZOrderDetail temp = r.DeepClone<AMZOrderDetail>();
                            temp.seller_name = x.seller_name;
                            var o = AMZOrders.Where(y => y.amazon_order_id == temp.amazon_order_id && y.seller_name == temp.seller_name);
                            temp.AmazonOrder = !o.IsNullOrEmpty() && o.Count() > 0 ? o.First().RowId : "";
                            temp.title = x.title;
                            temp.seller_sku = x.seller_sku;
                            temp.asin = x.asin;
                            temp.asin_url = x.asin_url;
                            temp.sku = x.sku;
                            temp.product_id = x.product_id;
                            temp.product_name = x.product_name;
                            temp.pic_url = x.title;
                            temp.order_item_id = x.order_item_id;
                            temp.points_monetary_value_amount = x.points_monetary_value_amount;
                            temp.quantity_ordered = x.quantity_ordered;
                            temp.quantity_shipped = x.quantity_shipped;
                            temp.item_price_amount = x.item_price_amount;
                            temp.item_tax_amount = x.item_tax_amount;
                            temp.shipping_price_amount = x.shipping_price_amount;
                            temp.shipping_tax_amount = x.shipping_tax_amount;
                            temp.gift_wrap_price_amount = x.gift_wrap_price_amount;
                            temp.gift_wrap_tax_amount = x.gift_wrap_tax_amount;
                            temp.shipping_discount_amount = x.shipping_discount_amount;
                            temp.cod_fee_amount = x.cod_fee_amount;
                            temp.promotion_ids = x.promotion_ids.IsNullOrEmpty() && x.promotion_ids.Count > 0 ? "" : String.Join(",", x.promotion_ids);
                            temp.shipping_discount_tax_amount = x.shipping_discount_tax_amount;
                            temp.promotion_discount_amount = x.promotion_discount_amount;
                            temp.promotion_discount_tax_amount = x.promotion_discount_tax_amount;
                            temp.cod_fee_discount_amount = x.cod_fee_discount_amount;
                            temp.gift_message_text = x.gift_message_text;
                            temp.gift_wrap_level = x.gift_wrap_level;
                            temp.condition_note = x.condition_note;
                            temp.condition_id = x.condition_id;
                            temp.condition_subtype_id = x.condition_subtype_id;
                            temp.scheduled_delivery_start_date = x.scheduled_delivery_start_date;
                            temp.scheduled_delivery_end_date = x.scheduled_delivery_end_date;
                            temp.price_designation = x.price_designation;
                            temp.cg_price = x.cg_price;
                            temp.fee_name = x.fee_name;
                            temp.cg_transport_costs = x.cg_transport_costs;
                            temp.fba_shipment_amount = x.fba_shipment_amount;
                            temp.commission_amount = x.commission_amount;
                            temp.other_amount = x.other_amount;
                            temp.fee_currency = x.fee_currency;
                            temp.fee_icon = x.fee_icon;
                            temp.fee_cost_amount = x.fee_cost_amount;
                            temp.fee_cost = x.fee_cost;
                            temp.sales_price_amount = x.sales_price_amount;
                            temp.unit_price_amount = x.unit_price_amount;
                            temp.tax_amount = x.tax_amount;
                            temp.promotion_amount = x.promotion_amount;
                            temp.profit = x.profit;
                            temp.item_discount = x.item_discount;
                            temp.ID = temp.amazon_order_id + temp.seller_name + temp.seller_sku;
                            sourceData.Add(temp);
                        });

                    });
                    //过滤重复项
                    var c = sourceData.GroupBy(x => x.ID).Where(x => x.Count() > 1);
                    //将重复的id编号变成唯一的id
                    sourceData.GroupBy(x => x.ID).ForEach(x =>
                    {
                        if (x.Count() > 1)
                        {
                            int c = 0;
                            x.ForEach(r =>
                            {
                                c++;
                                r.ID = r.ID + c;
                            });

                        }

                    });


                    //按照时间排序获取时间最早的一条记录
                    var sFrist = sourceData.OrderBy(x => x.purchase_date_local.ToDateTime()).First();
                    //获取目标数据
                    List<AMZOrderDetail> targetData = new List<AMZOrderDetail>();//目标据集合

                    this.Filters.Clear();
                    this.Filters.Add(
                        //13:>,14>=15:<,16<=  查询报表创建时间pull_date
                        new OL_FilterDTO()
                        {
                            ControlId = "676a2fd59e0bc69bf1877ba5",
                            DataType = 15,
                            SpliceType = 2,
                            FilterType = 14,
                            Value = sFrist.purchase_date_local.ToDateTime().ToString("yyyy-MM-dd"),
                        });
                    targetData = await QueryAsync<AMZOrderDetail>(queryOption, tableField, SqlDb);
                    targetData.ForEach(x =>
                    {
                        //订单明细
                        List<AssTable> table = new List<AssTable>();
                        if (!x.AmazonOrder.IsNullOrEmpty()) table = x.AmazonOrder.ToObject<List<AssTable>>();
                        if (table.Count > 0 && !table.IsNullOrEmpty()) x.AmazonOrder = table[0].sid;
                    });


                    if (this.State > 0 && sourceData.Count > 0)
                    {
                        //更新
                        #region
                        List<AMZOrderDetail> updataItem = sourceData.Intersect(targetData, new ComparerFromKeys<AMZOrderDetail>(Keys, "RowId")).ToList();//获取交集(更新项)
                        List<OL_RowDTO> updataData = ConvertOL_Row(updataItem, tableField);//需要更新的数据集合
                        ExecuteNoQuery<OL_RowDTO>(updataData, upDateOption, SqlDb);//执行更新
                        #endregion

                        //新增
                        #region
                        List<AMZOrderDetail> insertItem = sourceData.Except(targetData, new ComparerFromKey<AMZOrderDetail>(indexFields.First(), "RowId")).ToList();//获取源数据对目标数据的差集(新增项)
                        List<OL_RowDTO> insertData = ConvertOL_Row(insertItem, tableField);//需要新增的数据集合
                        ExecuteNoQuery<OL_RowDTO>(insertData, insertOption, SqlDb);//执行插入行
                        #endregion

                        //删除
                        #region
                        List<AMZOrderDetail> deleteItem = targetData.Except(sourceData, new ComparerFromKey<AMZOrderDetail>(indexFields.First(), "RowId")).ToList();//获取目标数对据源数据的差集(删除项)

                        List<AMZOrderDetail> repeatItem = targetData.GroupBy(x => x.GetPropertyValue(indexFields.First())).Where(x => x.Count() > 1).Select(x => x.FirstOrDefault()).ToList();
                        //将重复的项也一起加入删除的列表
                        deleteItem.AddRange(repeatItem);
                        //筛选出删除列表中重复的项
                        var temp = deleteItem.GroupBy(x => x.GetPropertyValue(indexFields.First())).Where(x => x.Count() > 1).Select(x => x.FirstOrDefault()).ToList();
                        deleteItem.AddRange(temp);

                        List<OL_RowDTO> deleteData = ConvertOL_Row(deleteItem, tableField);//需要删除的数据集合
                        ExecuteNoQuery<OL_RowDTO>(deleteData, deleteOption, SqlDb);//执行删除行
                        #endregion

                        //同步数据库
                        SqlDBInterfaceBusiness sqlDBInterface = new SqlDBInterfaceBusiness(Keys);
                        sqlDBInterface.ExecuteInterface<AMZOrderDetail>(sourceData, "SD_LX_AMZOrderDetail", $"WHERE purchase_date_local >= '{sFrist.purchase_date_local.ToDateTime().ToString("yyyy-MM-dd")}'");


                    }
                    else
                    {
                        throw new NotImplementedException("目标/源查询无数据无法执行接口!!");

                    }
                }
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 将源数据根据字典映射关系转换成OL_RowDTO
        /// </summary>
        /// <typeparam name="T">源数据</typeparam>
        /// <param name="sourceData">源数据</param>
        /// <param name="map">Key为目标字段名称，Value为源字段名称</param>
        /// <returns></returns>
        public List<OL_RowDTO> ConvertOL_Row<T>(List<T> sourceData, Dictionary<string, string> map)
        {
            List<OL_RowDTO> list = new List<OL_RowDTO>();
            object rowId;
            foreach (var item in sourceData)
            {
                rowId = item.GetPropertyValue("RowId");
                //需要新增的数据
                OL_RowDTO row = new OL_RowDTO() { RowId = rowId.IsNullOrEmpty() ? null : rowId.ToString(), Controls = new List<Control>() };
                foreach (var c in map)
                {
                    //判断对象的字段是否存在
                    if (item.ContainsProperty(c.Value))
                    {
                        //存在则添加数据
                        row.Controls.Add(new Control() { ControlId = c.Key, Value = item.GetPropertyValue(c.Value) });
                    }
                }
                list.Add(row);
            }
            return list;
        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
